<template>
  <a-card :style="{ boxShadow: 'none' }" :bordered="false" :bodyStyle="{ padding: '0' }">
    <a-table
      @change="pageChange"
      table-layout="fixed"
      sticky
      :row-selection="{
        selectedRowKeys: treeTable.keys,
        onChange: (k: any[]) => (treeTable.keys = k),
      }"
      bordered
      :loading="treeTable.loading"
      :pagination="false"
      :customRow="customRow"
      :rowKey="treeTable.rowKey"
      :columns="formatColumns(treeColumns)"
      :data-source="treeTable.data"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'operation'">
          <a-dropdown-button
            trigger="click"
            @click="treeEdit(record.id)"
            @open-change="openChange(record as AxTree)"
          >
            <EditOutlined />
            <template #overlay>
              <a-menu :items="treeTable.contextmenu"></a-menu>
            </template>
          </a-dropdown-button>
        </template>
      </template>
    </a-table>
  </a-card>
</template>

<script setup lang="ts">
import type { AxTree } from '@/api/modules/ax/tree/types';
import { formatColumns } from '@/utils/table/table';
import { useArrayFilter } from '@vueuse/core';
import type { TablePaginationConfig } from 'ant-design-vue';
import type { FilterValue, SorterResult } from 'ant-design-vue/es/table/interface';
import { treeColumns } from '../../data/column';
import { treeEdit, treeList } from '../../data/curd';
import { displayTreeMenu } from '../../data/curd';
import { treeFormConfig } from '../../data/form';
import { treeTable } from '../../data/table';
import { useCloned } from '@vueuse/core';

const openChange = (record: AxTree) => {
  treeFormConfig.value.form = useCloned(record).cloned.value;
};

/* 行事件 */
const customRow = (record: AxTree) => {
  return {
    onClick() {
      const id = (record as any)[treeTable.value.rowKey];
      treeFormConfig.value.form = record;
      if (!treeTable.value.keys.includes(id)) {
        treeTable.value.keys.push(id);
      } else {
        treeTable.value.keys = useArrayFilter(treeTable.value.keys, e => e !== id).value;
      }
      treeTable.value.keys = [record.id];
    },
    onDblclick() {
      treeEdit(record.id);
    },
    onContextmenu() {
      displayTreeMenu(record);
    },
  };
};

/* 分页事件触发 */
const pageChange = (
  pagination: TablePaginationConfig,
  filters: Record<string, FilterValue>,
  sorter: SorterResult<AxTree> | SorterResult<AxTree>[],
) => {
  if (pagination.current && pagination.pageSize) {
    treeTable.value.query.pageNum = pagination.current;
    treeTable.value.query.pageSize = pagination.pageSize;
  }
  if (!(sorter instanceof Array)) {
    treeTable.value.query.isAsc = sorter.order === 'ascend' ? 'asc' : 'desc';
  }
  treeList();
};
</script>

<style lang="scss" scoped></style>
